<template>
  <div class="app-container">
    <el-row :gutter="0">
      <el-col style="width: 60px; height: calc(100vh - 125px)">
        <div class="fixed-button-group" style="width: 60px;">
          <el-row>
          <!-- 新会话 -->
            <i class="el-icon-chat-dot-round custom2-button" @click="handleNewChat"><div style="font-size:12px">新对话</div></i>
          </el-row>
          <el-row>
          <!-- 历史会话 -->
            <i class="el-icon-time custom2-button" @click="handleShowHistory"><div style="font-size:12px">历史</div></i>
          </el-row>
        </div>
      </el-col>
      <el-col :style="{ width: 'calc(100% - 60px)' }">
        <div style="background-color: #d3dce6">
          <el-card>
            <div slot="header" class="clearfix">
              <el-row :gutter="0">
                <el-col :span="8">
                  <span>{{agentInfo.vDesc}}<el-button style="padding: 3px 0" type="text" @click="handleSelectAIAgent">选择模型</el-button></span>
                </el-col>
                <el-col :span="8">
                  <div  style="text-align:center;align-content:center;">{{title}}</div>
                </el-col>
                <el-col :span="8">
                </el-col>
              </el-row>
            </div>
<!--            <div slot="header" class="clearfix" style="display:flex;justify-content:space-between;">-->
<!--              <span>{{agentInfo||''}}<el-button style="float: right; padding: 3px 0" type="text" @click="handleSelectAIAgent">选择模型</el-button></span>-->
<!--              <span  style="text-align:center;">{{title}}</span>-->
<!--            </div>-->
            <Chat ref="chat" :messages="messages" @ask-again="handleAskAgain" @delete="handleDeleteMessages"/>
            <div class="input-area">
              <el-input
                v-model="input"
                placeholder="请输入您的问题..."
                @keyup.ctrl.enter.native="sendMessage"
                @input="handleInput"
                class="input-field"
                type="textarea"
                :rows="3"
                :style="{ maxWidth: 'calc(100% - 100px)' }"
              ></el-input>
              <el-button :loading="msgLoading" type="primary" @click="sendMessage">发送</el-button>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <ChatSelectAiAgentDialog ref="ChatSelectAiAgentDialogRef"/>
    <ShowChatHistoryDialog ref="ShowChatHistoryDialogRef"/>

  </div>
</template>

<script>
import store from "@/store";
import { addMessage, changeChatAiAgent, chatSendMessage, deleteMessage, getAIChatDetail, getLastChat } from '@/api/chat'
import Chat from '@/views/chat/Chat.vue'
import { chatMessageRoleEnum } from '@/utils/dicts'
import { deleteFromVueVirtualUUID, numberIsZeroOrNull } from 'sks-plugin-el-erp/lib/core'
import ChatSelectAiAgentDialog from './chat-select-ai-agent-dialog.vue'
import { saveChatMyInput } from '@/utils/chat'
import ShowChatHistoryDialog from '@/views/chat/show-chat-history-dialog.vue'

export default {
  components:{
    ShowChatHistoryDialog,
    Chat,
    ChatSelectAiAgentDialog,
  },
  data() {
    return {
      agentInfo: {
        ai_agent_id: undefined,
        vDesc: ''
      },
      chatId: undefined,
      title: '新会话',
      input: '',
      messages: [],
      avatar: store.getters.avatar,
      avatar_bot: require('@/assets/images/robot.png'),
      msgLoading: false,
    };
  },
  created() {
    this.getLastChat()
  },
  mounted() {
    this.input=this.chatUtils.loadChatMyInput()
    this.getLastChat()
  },
  methods: {
    getLastChat(){
      getLastChat().then(res=>{
        if(res.data){
          res.data.messages.forEach(item=>{
            const vueVirtualUUID = this.sksUtils.generateUUID()
            item.vueVirtualUUID=vueVirtualUUID
            if(item.role==chatMessageRoleEnum.assistant) {
              item.avatar = this.avatar_bot
            }else if(item.role==chatMessageRoleEnum.user){
              item.avatar=this.avatar
            }
          })
          this.messages = res.data.messages
          this.chatId=res.data.chat_id
          this.title=res.data.title
          this.agentInfo=res.data.agentInfo
        }else{
          this.handleNewChat()
        }
      })
    },
    sendMessage() {
      console.log('消息:', this.input);
      if (this.input.trim() === '') return;
      if(numberIsZeroOrNull(this.agentInfo.ai_agent_id)){
        this.sksUtils.msgError("请先选择[助手]模型")
        return
      }
      const userInput = this.input;
      this.msgLoading = true
      const vueVirtualUUID = this.sksUtils.generateUUID()
      let userMsg={
        vueVirtualUUID: vueVirtualUUID,
        role: this.dicts.chatMessageRoleEnum.user,
        content: userInput,
        chat_id: this.chatId,
        avatar: this.avatar
      }

      this.messages.push(userMsg)

      let data={
        ai_agent_id: this.agentInfo.ai_agent_id,
        vueVirtualUUID: vueVirtualUUID,
        role: this.dicts.chatMessageRoleEnum.user,
        content: userInput,
        chat_id: this.chatId,
      }
      addMessage(data).then(res => {
        let resData=res.data
        if(numberIsZeroOrNull(this.chatId)){
          this.chatId=resData.chat_id
          this.title=resData.title
        }
        resData.avatar=this.avatar
        this.messages.some((item,i)=>{
          if(item.vueVirtualUUID==resData.vueVirtualUUID){
            item.id=resData.id
            item.content=resData.content
            item.role=resData.role
            item.avatar=this.avatar
            this.$set(this.messages, i, item)
            return true
          }
        })
        this.chatSendMessage(resData)
      });
    },
    chatSendMessage(message){
      const vueVirtualUUID= this.sksUtils.generateUUID()
      // 添加加载状态的消息
      let botMsg = {
        vueVirtualUUID: vueVirtualUUID,
        avatar: this.avatar_bot,
        role: this.dicts.chatMessageRoleEnum.assistant,
        content: '',
        loading: true
      }
      this.messages.push(botMsg)

      let data = {
        vueVirtualUUID: vueVirtualUUID,
        problem_id: message.id,
        chat_id: this.chatId,
        content: message.content,
      };

      chatSendMessage(data).then(res => {
        let resData=res.data
        this.messages.some((item,i)=>{
          if(item.vueVirtualUUID==resData.vueVirtualUUID){
            item.content = resData.content
            item.id=resData.id
            item.role=resData.role
            item.loading=false
            this.$set(this.messages, i, item)
            console.log('chatSendMessage ok',i,this.messages)
            return true
          }
        })
        this.msgLoading = false
        this.scrollToBottom();
      }).catch(err => {
        console.log(err);
        this.messages.some((item,i)=>{
          if(item.vueVirtualUUID==vueVirtualUUID){
            item.content= err
            item.loading=false
            this.$set(this.messages, i, item)
            return true
          }
        })
        this.msgLoading = false
      });

      // 清空输入框
      this.input = '';//现在调试,不清除
      this.chatUtils.removeChatMyInput()
      this.scrollToBottom();
    },
    handleDeleteMessages(msg,index){
      deleteMessage(msg.id).then(res=>{
        //删除我的问题
        this.messages.splice(index, 1);
        if(this.messages.length>index){
          //同时删除bot的回答
          if(this.messages[index].role==chatMessageRoleEnum.assistant){
            this.messages.splice(index, 1);
            return
          }
        }
      })
      // this.
    },
    scrollToBottom() {
      this.$refs.chat.scrollToBottom();
    },
    handleAskAgain(msg){
      console.log("handleAskAgain")
      this.input=msg
    },
    handleNewChat(){
      //使用上次对话的智能体
      if(this.sksUtils.isNullOrUndefined(this.agentInfo)){
        this.agentInfo={
          ai_agent_id: undefined,
          vDesc: ''
        }
      }
      this.messages=[]
      this.title=''
      this.chatId=undefined
      console.log('handleNewChat')
    },
    handleShowHistory(){
      this.$refs.ShowChatHistoryDialogRef.showToSelect({
        dialogInfo: {
          title: '历史对话',
          deleteSuccessCallback: ({chatIds})=>{
            for (let chatId of chatIds){
              if(chatId==this.chatId){
                this.handleNewChat()
              }
            }
          },
          selectCallback: ({selectRow,ref})=>{
            let data={
              id: selectRow.id,
            }
            getAIChatDetail(data).then(res=>{
              if(res.data){
                res.data.messages.forEach(item=>{
                  const vueVirtualUUID = this.sksUtils.generateUUID()
                  item.vueVirtualUUID=vueVirtualUUID
                  if(item.role==chatMessageRoleEnum.assistant) {
                    item.avatar = this.avatar_bot
                  }else if(item.role==chatMessageRoleEnum.user){
                    item.avatar=this.avatar
                  }
                })
                this.messages = res.data.messages
                this.chatId=res.data.chat_id
                this.title=res.data.title
                this.agentInfo=res.data.agentInfo
              }
            })
            ref.closeDialog();
          }
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.none,
      })
    },
    handleSelectAIAgent(){
      this.$refs.ChatSelectAiAgentDialogRef.showToSelect({
        dialogInfo: {
          title: '设置模型',
          selectCallback: ({selectRow,ref})=>{
            let data={
              chat_id: this.chatId,
              ai_agent_id: selectRow.id,
            }
            changeChatAiAgent(data).then(res=>{
              this.agentInfo=res.data
              ref.closeDialog();
            })
          }
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.none,
      })
    },
    handleInput(value){
      this.chatUtils.saveChatMyInput(value)
    },
  }
};
</script>

<style scoped>
.app-container {
  height: 100%;
  padding: 20px;
  padding-left: 0px;
}
.input-area {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.input-field {
  flex: 1;
  margin-right: 10px;
  max-width: calc(100% - 100px);
}
/*
background-color: #99a9bf;
 */
.fixed-button-group{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.custom2-button {
  font-size: 24px; /* 放大图标 */
  border: none; /* 移除边框 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
}
</style>



